import cv2
import imutils
import pytesseract
 
def plate_recognition(image_path):
    # 加载图片
    image = cv2.imread(image_path)
    # 转换为灰度图
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # 使用Sobel算子进行边缘检测
    sobel = cv2.Sobel(gray, cv2.CV_8U, 1, 0, ksize=5)
    # 二值化
    binary = cv2.threshold(sobel, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
    # 形态学变换 - 用于去除噪声
    binary = cv2.morphologyEx(binary, cv2.MORPH_RECT, (13,3))
    # 寻找轮廓
    contours, _ = cv2.findContours(binary.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    # 按面积排序
    contours = sorted(contours, key=cv2.contourArea, reverse=True)[:5]
    # 遍历轮廓
    for contour in contours:
        # 近似轮廓
        peri = cv2.arcLength(contour, True)
        approx = cv2.approxPolyDP(contour, 0.02 * peri, True)
        # 如果近似轮廓有4个点，可能是车牌
        if len(approx) == 4:
            # 画出轮廓
            cv2.drawContours(image, [approx], -1, (0, 255, 0), 3)
            # 裁剪车牌区域
            x, y, w, h = cv2.boundingRect(approx)
            plate = image[y:y+h, x:x+w]
            # 缩放车牌图片以适应Tesseract的输入要求
            plate = cv2.resize(plate, (500, 150))
            # 使用Tesseract进行字符识别
            text = pytesseract.image_to_string(plate, config='--psm 6')
            print(text)
            # 画出识别的字符
            cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
            cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
    # 显示图片
    cv2.imshow("Plate Recognition", image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
 
# 调用函数进行车牌识别
plate_recognition('D:/wwwroot/Python/tool/20240826133950.jpg')